import React from 'react'
import { Table,Button,Modal,Select, message } from 'antd';
import { getUserApi,getDeptApi,delUserApi,restPswApi } from '../../../apis/user';
import type { TableProps } from 'antd/es/table';
import type { ColumnsType, FilterValue} from 'antd/es/table/interface';
import { SettingOutlined, EyeOutlined, FallOutlined,UserOutlined,HomeOutlined,PhoneOutlined,StarOutlined,LoginOutlined,FieldTimeOutlined,MailOutlined,SkinOutlined,SmileOutlined,ExclamationCircleFilled} from '@ant-design/icons';
import UserSearch from './UserSearch';
import('./user.less')
const { confirm } = Modal;
// 导入抽屉组件
import DrawerInfo from './DrawerInfo';
export default function user() {
  //表格数据
  const [list, setList] = React.useState([]);
  //部门数据
  const [deptData, setDeptData] = React.useState([])
  //加载中
  const [loading, setLoading] = React.useState(true)
  //总条数
  const [total, setTotal] = React.useState(0)
  //筛选相关
  const [filteredInfo, setFilteredInfo] = React.useState<Record<string, FilterValue | null>>({});
  //排序相关
  // const [sortedInfo, setSortedInfo] = React.useState<SorterResult<DataType>>({});
  //控制模态框
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  //scope数据
  const [scopeData, setScopeData] = React.useState<any>({});
  //表格选中
  const [selectedRows, setSelectedRows] = React.useState([])
  //抽屉组件开关
  const [open, setOpen] = React.useState(false)
  //修改信息用户数据
  const [userData, setUserData] = React.useState({})
  //子组件标题初始化数据
  const [title, setTitle] = React.useState('新增用户')
  const[isUpdate,setIsUpdate]=React.useState(false)
  //表格数据约束接口
  interface DataType {
    key: React.Key;
    username: string;
    ssex: string;
    email: string;
    deptId: number;
    mobile: string;
    status: string;
    createTime: string;
  }
  //列约束及数据
  const columns: ColumnsType<DataType> = [
    {
      title: '用户名',
      dataIndex: 'username',
      sorter: (a:any, b:any) => a.username.length - b.username.length,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      filters: [
        {text:'男',value:'0'},
        {text:'女',value:'1'},
        {text:'保密',value:'2'},
      ],
      filteredValue: filteredInfo.ssex || null,
      onFilter:(value:any,record:any)=>record.ssex==value,
      render(text: string) {
        switch (text) {
          case "0":
            return "男";
          case "1":
            return "女"
          default: return "保密"
        }
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptId',
      render(text: any) {
        switch (text) {
          case 1:
            return "开发部";
          case 2:
            return "开发一部"
            case 3:
            return "开发二部"
            case 4:
            return "市场部"
            case 5:
            return "人事部"
            case 6:
            return "测试部"
          default: return "暂无数据"
        }
      }
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      filters: [
        { text: '有效', value: '1' },
        { text: '锁定', value: '0' },
        
      ],
      filteredValue: filteredInfo.status || null,
      onFilter: (value: any, record: any) => record.status.includes(value),
      render:(_,scoped:any)=>(scoped.status=='1'?<Button className='tab-btn-green' size={'small'}>有效</Button> :
      <Button className='tab-btn-red' size={'small'}>锁定</Button>),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: (a: any, b: any) => a.createTime - b.createTime,
      
    },
    {
      title: '操作',
      render: (_, scoped) => (<>
        <SettingOutlined style={{ marginRight: '8px', fontSize: '16px', color: '#08c', cursor: 'pointer' }} onClick={ ()=>addUser(scoped)}/>
        <EyeOutlined style={{ fontSize: '16px', color: '#52c41a', cursor: 'pointer' }} onClick={ ()=>showUserModal(scoped)} />
      </>)
    },
  ];
  //打开模态框
  function showUserModal(scoped:any){
    setIsModalOpen(true);
    setScopeData(scoped)
  }
  //关闭模态框
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //改变分页
  function onChange(pageNum: any,pageSize:any) {
     console.log('你',pageNum,pageSize)
     getData({pageNum})
  }
  //获取数据方法
  function getData(params?:any) {
    getUserApi(params).then(res => {
      setList(res.rows)
      setTotal(res.total)
      setLoading(false)
    })
  }
  const handleChange: TableProps<DataType>['onChange'] = (pagination, filters, sorter) => {
    setFilteredInfo(filters)
  };
  //接口发送数据
  React.useEffect(() => {
    getData()
    getDept()
  }, [])
  function getDept() {
    getDeptApi().then(res => {
      setDeptData(res.rows.children)
    })
  }
  //处理性别
  function setSex(ssex:any) {
    switch (ssex) {
      case "0":
        return "男"
        break;
      case "1":
        return "女"
        case "2":
          return "保密"
      default:
        return "暂无数据"
        break;
    }
  }
  //选中
  const rowSelection:any = {
    onChange: (_: string, value: []) => {
     
      setSelectedRows(value)
    },
  };
  //删除用户
  function delUser() {
    if (!selectedRows.length) {
      message.error('请先选择数据')
    } else {
      selectedRows.forEach((item: any, index) => {
        
        delUserApi(item.userId).then(
          res => {
            message.success('删除成功')
            getData()
          }
        ).catch(err => {
          message.error('删除失败')
        })
      })
    }
  }
  //重置密码或者导出excel
  function resetExcel(value:string) {
    if (value == '0') {
      restPassword()
    } 
    if (value == '1') {
      console.log('导出excel')
    } 
  }
  function restPassword() {
    if (!selectedRows.length) {
      message.error('请选择数据')
    } else {
      confirm({
        title: '你想重置这条数据吗',
        icon: <ExclamationCircleFilled />,
        content: '点击确认后,密码将被初始化为1234qwer',
        onOk() {
          selectedRows.forEach((item: any, index) => {
            
            restPswApi({usernames:item.username}).then(res => {
             
              message.success('密码重置成功')
           })
          })
        },
        onCancel() {
         message.info('取消重置')
        },
      });
    }
  }
  //新增,修改用户
  function addUser(scoped?:any) {
    setOpen(true)
    //编辑用户
    if (scoped.userId) {
      setTitle('编辑用户')
      setIsUpdate(true)
      //userData是传给子抽屉组件的用来修改的用户数据数据，因为roleId数据类型不匹配,组件无法回显数据
      //因此进行处理,先用split逗号分隔开，然后遍历成Number数据类型
      setUserData({...scoped,roleId:scoped.roleId?.split(',').map(Number)})
    } else {
      setTitle('新增用户')
      setIsUpdate(false)
      setUserData([])
    }
    
  }
  return (
    <div>
      <UserSearch deptData={deptData} getData={getData} />
      <Button onClick={addUser} style={{ margin: '0 10px 16px 0' }}>新增</Button>
      <Button onClick={delUser} style={{ marginRight: '10px' }}>删除</Button>
      <Select
      value={'更多操作'}
      style={{ width: 100 }}
      onChange={resetExcel}
      options={[
        {
          value: '0',
          label: '密码重置',
        },
        {
          value: '1',
          label: '导出Excel',
        },
      ]}
      />
      <Table columns={columns} dataSource={list}
        rowKey="userId"
        pagination={{ total, onChange }}
        loading={loading}
        rowSelection={rowSelection}
        onChange={handleChange}
      />
      <Modal title="用户信息" open={isModalOpen} onCancel={handleCancel} footer={false}
        className="helloModal"
        width={700}
      >
        <div className='modalContainer'>
          <div className="left">
            <img src="http://xawn.f3322.net:8002/distremote/static/avatar/2dd7a2d09fa94bf8b5c52e5318868b4d9.jpg" alt="" />
          </div>
          <div className="middle">
            <div className="middleItem">
            <UserOutlined />
              <p>用户名&nbsp;&nbsp;&nbsp;{ scopeData.username}</p>
            </div>
            <div className="middleItem">
            <HomeOutlined />
              <p>部门&nbsp;&nbsp;&nbsp;{scopeData.deptName }</p>
            </div>
            <div className="middleItem">
            <PhoneOutlined />
              <p>电话&nbsp;&nbsp;&nbsp;{ scopeData.mobile}</p>
            </div>
            <div className="middleItem">
            <StarOutlined />
              <p>角色&nbsp;&nbsp;&nbsp;{scopeData.roleName }</p>
            </div>
            <div className="middleItem">
              <FallOutlined />
              <p>状态:&nbsp;&nbsp;&nbsp;{ scopeData.status=='1'?<Button className='tab-btn-green' size={'small'}>有效</Button> :
      <Button className='tab-btn-red' size={'small'}>锁定</Button>}</p>
            </div>
            <div className="middleItem">
            <SkinOutlined />
              <p>性别:&nbsp;&nbsp;&nbsp;{
              setSex(scopeData.ssex)
              }</p>
            </div>
            <div className="middleItem">
            <FieldTimeOutlined />
              <p>创建时间&nbsp;&nbsp;&nbsp;{ scopeData.createTime}</p>
            </div>
            <div className="middleItem">
              
              <LoginOutlined/>
              <p>最近登录&nbsp;&nbsp;&nbsp;{ scopeData.lastLoginTime}</p>
            </div>
            <div className="middleItem">
            <MailOutlined />
              <p>邮箱&nbsp;&nbsp;&nbsp;{scopeData.email}</p>
            </div>
            <div className="middleItem">
            <SmileOutlined />
              <p>描述&nbsp;&nbsp;&nbsp;{ scopeData.description}</p>
            </div>

          </div>
        </div>
      </Modal>
      <DrawerInfo
        open={open}
        setOpen={setOpen}
        userData={userData}
        setUserData={setUserData}
        title={title}
        isUpdate={isUpdate}
        deptData={deptData}
        getData={getData}
      />
    </div>
  )
}
